/**
 * 处理鼠标按下或手指按下
 * @param {MouseEvent|TouchEvent} e - 事件参数对象
 */
function handleMouseDownOrTouchStart(e) {
  let { x, y } = getPosition(e)
  lastDot.x = x
  lastDot.y = y
  // 鼠标按下开启画笔
  enablePainting = true
}

/**
 * 处理鼠标移动或手指移动
 * @param {MouseEvent|TouchEvent} e - 事件参数对象
 */
function handleMouseMoveOrTouchMove(e) {
  let { x, y } = getPosition(e)
  if (enableEarser) {
    canvas.getContext('2d').clearRect(x, y, 16, 16)
    return
  }
  // 没有开启画笔，直接return，啥也不做
  if (!enablePainting) return

  // 开启了画笔
  newDot.x = x
  newDot.y = y
  drawCircle(canvas, {
    x,
    y,
    radius: 2,
    paintingColor,
  })
  drawLine(canvas, {
    x1: lastDot.x,
    y1: lastDot.y,
    x2: newDot.x,
    y2: newDot.y,
    lineWidth,
    paintingColor,
  })
  // 更新lastDot，让lastDot始终为上一个点的位置
  lastDot.x = newDot.x
  lastDot.y = newDot.y
}

/**
 * 处理鼠标抬起或手指离开
 */
function handleMouseUpOrTouchEnd() {
  // 鼠标抬起禁用画笔
  enablePainting = false
  // 鼠标抬起禁用橡皮擦
  enableEarser = false
  earser.querySelector('path').style.fill = '#aaa'
}

/**
 * 开启橡皮擦要做的事
 */
function handleEnableEarser() {
  enableEarser = !enableEarser
  if (enableEarser) {
    earser.querySelector('path').style.fill = '#23aaf2'
  } else {
    earser.querySelector('path').style.fill = '#aaa'
  }
}

/**
 * 清楚全部画的内容
 */
function handleClear() {
  canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height)
}

/**
 * 将canvas画布保存为png
 * 方法来自 Stack Overflow -- by noontz
 * https://stackoverflow.com/questions/11112321/how-to-save-canvas-as-png-image
 * @param {HTMLCanvasElement} canvas - canvas画布
 */
function DownloadCanvasAsImage(canvas) {
  let downloadLink = document.createElement('a')
  downloadLink.setAttribute('download', '小小画板.png')
  canvas.toBlob(function (blob) {
    let url = URL.createObjectURL(blob)
    downloadLink.setAttribute('href', url)
    downloadLink.click()
  })
}
